<?php

declare(strict_types=1);

namespace App\Controller;

use App\Job\IotEvent;
use App\Model\Normal;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnReceiveInterface;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class TcpServer implements OnReceiveInterface,OnCloseInterface
{

    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('log', 'device');
    }

    /**
     * 处理连接建立事件
     */
    public function onConnect($server, int $fd, int $reactorId): void
    {
        try{
            $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('iot-event');
            $driver->push(new IotEvent($fd,'open'));
        }catch (\Exception $e){
            Normal::logger('fd----error'. $e->getMessage() . $e->getTraceAsString(), 'notify-event');
        }
    }

    /**
     * 处理数据接收事件
     */
    public function onReceive($server, int $fd, int $reactorId, string $data): void
    {
        // 记录设备日志
        // 解析
        try{
            $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('iot-event');
            $driver->push(new IotEvent($fd,'recv',$data));
        }catch (\Exception $e){
            Normal::logger('fd----error'. $e->getMessage() . $e->getTraceAsString(), 'notify-event');
        }
    }

    /**
     * 处理连接关闭事件
     */
    public function onClose($server, int $fd, int $reactorId): void
    {
        try {
            $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('iot-event');
            $driver->push(new IotEvent($fd,'close'));
        }catch (\Exception $e){
            Normal::logger('fd.---not---queue'. $e->getMessage() . $e->getTraceAsString(), 'notify-event');
        }
    }
}
